package com.itheima.chapter03.controller;

import com.itheima.chapter03.domain.AjaxResult;
import com.itheima.chapter03.domain.Article;
import com.itheima.chapter03.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 控制器有两种： Controller
 * -->  RestController
 */

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

//    @GetMapping("/article")
    @GetMapping
    public AjaxResult list() {
        return AjaxResult.success(articleService.list(new Article()));
    }

//    @PostMapping("/article")
    @PostMapping
    public AjaxResult insert(@Validated @RequestBody Article article) {
        // 校验数据是否有效
//        if (StringUtils.isBlank(article.getTitle())) {
//            return AjaxResult.error("标题不能为空");
//        }
//        if (StringUtils.isBlank(article.getContent())) {
//            return AjaxResult.error("内容不能为空");
//        }
        int ret = articleService.insert(article);
        if (ret > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

//    @DeleteMapping("/article/{id}")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Integer id) {
        if (id <= 0) {
            return AjaxResult.error("id不能小于0");
        }
        int ret = articleService.delete(id);
        if (ret > 0)
            return AjaxResult.success();
        else
            return AjaxResult.error();
    }

//    @GetMapping("/article/{id}")
    @GetMapping("/{id}")
    public AjaxResult select(@PathVariable Integer id) {
        if (id <= 0) {
            return AjaxResult.error("id不能小于0");
        }
        Article article = articleService.selectById(id);
        return AjaxResult.success(article);
    }
}
